#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <assert.h>
#include <sys/mman.h>
#include "defs.h"
#include "lock.h"

team_t team = {
    "HanSolo",           /* Team name */
    "Mustafa Abbas",      /* First member full name */
    "996055423",  /* First member student number */
    "",                   /* Second member full name (leave blank if none) */
    ""                    /* Second member student number (leave blank if none) */
};

// Initialization
void 
mutex_init(mutex_t *mutex){
    *mutex = 0;
}

// Test-and-Set lock
#ifdef TS_LOCK
asm(
".text\n"
".balign 8\n"
".globl mutex_lock\n"
"mutex_lock:\n"
   "mov 4(%esp), %eax;"
"10:"
   "lock; bts $0, (%eax);"
   "jc 10b;"
   "ret;"
);
#endif // TS_LOCK

// Test-and-Test-and-Set lock
#ifdef TTS_LOCK
asm(
".text\n"
".balign 8\n"
".globl mutex_lock\n"
"mutex_lock:\n"
   "mov 4(%esp), %eax;"
"11:"
   "bt $0, (%eax);"
   "jc 11b;"
   "lock; bts $0, (%eax);"
   "jc 11b;"
   "ret;"
);
#endif //TTS_LOCK

// Test-and-Test-and-Set lock with backoff
#ifdef TTS_BACKOFF_LOCK
asm(
".text\n"
".balign 8\n"
".globl mutex_lock\n"
"mutex_lock:\n"
   "mov 4(%esp), %eax;"
"1:"
   "bt $0, (%eax);"
   "jc 2f;"
   "lock; bts $0, (%eax);"
   "jnc 6f;"
"2:"
   "movl $9, %edx;"
"3:"
   "mov %edx, %ecx;"
"4:"
   "sub $1, %ecx;"
   "jne 4b;"
   "bt $0, (%eax);"
   "jc 5f;"
   "lock; bts $0, (%eax);"
   "jnc 6f;"
"5:"
   "add %edx, %edx;"
   "jmp 3b;"

"6:"
   "ret;"
);
#endif //TTS_BACKOFF_LOCK

// Unlock
asm(
".text\n"
".balign 8\n"
".globl mutex_unlock\n"
"mutex_unlock:\n"
// Get lock pointer
    "mov 4(%esp), %edx;"
// Release lock 
    "add $1, (%edx);"
    "ret;"
);

void barrier_init(barrier_t *barrier, int nthreads){
}

void barrier_wait(barrier_t *barrier){
}
